using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Collections.Concurrent;
using SeataNet.Core.Common;

namespace SeataNet.Core.Monitor
{
    /// <summary>
    /// 事务监控器接口
    /// </summary>
    public interface ITransactionMonitor
    {
        /// <summary>
        /// 记录事务状态
        /// </summary>
        /// <param name="transactionId">事务ID</param>
        /// <param name="status">事务状态</param>
        void RecordTransaction(string transactionId, TransactionStatus status);

        /// <summary>
        /// 记录分支状态
        /// </summary>
        /// <param name="branchId">分支ID</param>
        /// <param name="status">分支状态</param>
        void RecordBranch(long branchId, BranchStatus status);

        /// <summary>
        /// 记录事务开始
        /// </summary>
        /// <param name="xid">全局事务ID</param>
        /// <param name="transactionName">事务名称</param>
        /// <param name="branchType">分支类型</param>
        void RecordTransactionBegin(string xid, string transactionName, string branchType);

        /// <summary>
        /// 记录事务提交
        /// </summary>
        /// <param name="xid">全局事务ID</param>
        /// <param name="duration">持续时间（毫秒）</param>
        void RecordTransactionCommit(string xid, long duration);

        /// <summary>
        /// 记录事务回滚
        /// </summary>
        /// <param name="xid">全局事务ID</param>
        /// <param name="duration">持续时间（毫秒）</param>
        /// <param name="exception">异常信息</param>
        void RecordTransactionRollback(string xid, long duration, Exception? exception = null);

        /// <summary>
        /// 记录分支事务注册
        /// </summary>
        /// <param name="xid">全局事务ID</param>
        /// <param name="branchId">分支ID</param>
        /// <param name="resourceId">资源ID</param>
        /// <param name="branchType">分支类型</param>
        void RecordBranchRegister(string xid, long branchId, string resourceId, string branchType);

        /// <summary>
        /// 记录分支事务提交
        /// </summary>
        /// <param name="xid">全局事务ID</param>
        /// <param name="branchId">分支ID</param>
        void RecordBranchCommit(string xid, long branchId);

        /// <summary>
        /// 记录分支事务回滚
        /// </summary>
        /// <param name="xid">全局事务ID</param>
        /// <param name="branchId">分支ID</param>
        /// <param name="exception">异常信息</param>
        void RecordBranchRollback(string xid, long branchId, Exception? exception = null);

        /// <summary>
        /// 获取事务统计信息
        /// </summary>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns>事务统计信息</returns>
        TransactionStatistics GetTransactionStatistics(DateTime startTime, DateTime endTime);

        /// <summary>
        /// 获取事务性能指标
        /// </summary>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <returns>事务性能指标</returns>
        TransactionMetrics GetTransactionMetrics(DateTime startTime, DateTime endTime);

        /// <summary>
        /// 获取活跃事务列表
        /// </summary>
        /// <returns>活跃事务列表</returns>
        List<ActiveTransaction> GetActiveTransactions();

        /// <summary>
        /// 获取事务详情
        /// </summary>
        /// <param name="xid">全局事务ID</param>
        /// <returns>事务详情</returns>
        TransactionDetail? GetTransactionDetail(string xid);

        /// <summary>
        /// 获取当前指标
        /// </summary>
        /// <returns>事务指标</returns>
        TransactionMetrics GetMetrics();

        /// <summary>
        /// 重置指标
        /// </summary>
        void ResetMetrics();
    }

    /// <summary>
    /// 默认事务监控器实现
    /// </summary>
    public class DefaultTransactionMonitor : ITransactionMonitor
    {
        private readonly ILogger<DefaultTransactionMonitor> _logger;
        private readonly IOptionsMonitor<MonitorConfiguration> _configuration;
        private readonly ConcurrentDictionary<string, TransactionMetrics> _transactionMetrics;
        private readonly ConcurrentDictionary<string, ActiveTransaction> _activeTransactions;
        private readonly ConcurrentDictionary<string, List<BranchMetrics>> _branchMetrics;
        private readonly object _statisticsLock = new object();
        private TransactionStatistics _statistics;

        public DefaultTransactionMonitor(
            ILogger<DefaultTransactionMonitor> logger,
            IOptionsMonitor<MonitorConfiguration> configuration)
        {
            _logger = logger;
            _configuration = configuration;
            _transactionMetrics = new ConcurrentDictionary<string, TransactionMetrics>();
            _activeTransactions = new ConcurrentDictionary<string, ActiveTransaction>();
            _branchMetrics = new ConcurrentDictionary<string, List<BranchMetrics>>();
            _statistics = new TransactionStatistics();

            // 启动后台清理任务
            Task.Run(async () => await CleanupTaskAsync());
        }

        public void RecordTransactionBegin(string xid, string transactionName, string branchType)
        {
            var now = DateTime.UtcNow;
            var activeTransaction = new ActiveTransaction
            {
                Xid = xid,
                TransactionName = transactionName,
                BranchType = branchType,
                StartTime = now,
                Status = TransactionMonitorStatus.Active
            };

            _activeTransactions.TryAdd(xid, activeTransaction);

            // 更新统计信息
            lock (_statisticsLock)
            {
                _statistics.TotalTransactions++;
                _statistics.ActiveTransactions++;
            }

            _logger.LogDebug("Transaction begin recorded, XID: {Xid}, TransactionName: {TransactionName}", 
                xid, transactionName);
        }

        public void RecordTransactionCommit(string xid, long duration)
        {
            if (_activeTransactions.TryRemove(xid, out var activeTransaction))
            {
                activeTransaction.EndTime = DateTime.UtcNow;
                activeTransaction.Status = TransactionMonitorStatus.Committed;
                activeTransaction.Duration = duration;

                // 更新事务指标
                var metrics = _transactionMetrics.GetOrAdd(xid, _ => new TransactionMetrics
                {
                    Xid = xid,
                    TransactionName = activeTransaction.TransactionName,
                    BranchType = activeTransaction.BranchType,
                    StartTime = activeTransaction.StartTime,
                    EndTime = activeTransaction.EndTime ?? DateTime.UtcNow,
                    Duration = duration,
                    Status = TransactionMonitorStatus.Committed
                });

                // 更新统计信息
                lock (_statisticsLock)
                {
                    _statistics.ActiveTransactions--;
                    _statistics.CommittedTransactions++;
                    _statistics.TotalDuration += duration;
                    _statistics.MaxDuration = Math.Max(_statistics.MaxDuration, duration);
                    _statistics.MinDuration = _statistics.MinDuration == 0 ? duration : Math.Min(_statistics.MinDuration, duration);
                }

                _logger.LogDebug("Transaction commit recorded, XID: {Xid}, Duration: {Duration}ms", 
                    xid, duration);
            }
        }

        public void RecordTransactionRollback(string xid, long duration, Exception? exception = null)
        {
            if (_activeTransactions.TryRemove(xid, out var activeTransaction))
            {
                activeTransaction.EndTime = DateTime.UtcNow;
                activeTransaction.Status = TransactionMonitorStatus.RolledBack;
                activeTransaction.Duration = duration;
                activeTransaction.Exception = exception;

                // 更新事务指标
                var metrics = _transactionMetrics.GetOrAdd(xid, _ => new TransactionMetrics
                {
                    Xid = xid,
                    TransactionName = activeTransaction.TransactionName,
                    BranchType = activeTransaction.BranchType,
                    StartTime = activeTransaction.StartTime,
                    EndTime = activeTransaction.EndTime ?? DateTime.UtcNow,
                    Duration = duration,
                    Status = TransactionMonitorStatus.RolledBack,
                    Exception = exception
                });

                // 更新统计信息
                lock (_statisticsLock)
                {
                    _statistics.ActiveTransactions--;
                    _statistics.RolledBackTransactions++;
                    _statistics.TotalDuration += duration;
                    _statistics.MaxDuration = Math.Max(_statistics.MaxDuration, duration);
                    _statistics.MinDuration = _statistics.MinDuration == 0 ? duration : Math.Min(_statistics.MinDuration, duration);
                }

                _logger.LogDebug("Transaction rollback recorded, XID: {Xid}, Duration: {Duration}ms, Exception: {Exception}", 
                    xid, duration, exception?.Message);
            }
        }

        public void RecordBranchRegister(string xid, long branchId, string resourceId, string branchType)
        {
            var branchMetrics = new BranchMetrics
            {
                Xid = xid,
                BranchId = branchId,
                ResourceId = resourceId,
                BranchType = branchType,
                StartTime = DateTime.UtcNow,
                Status = BranchStatus.Registered
            };

            _branchMetrics.AddOrUpdate(xid, 
                new List<BranchMetrics> { branchMetrics }, 
                (key, list) => { list.Add(branchMetrics); return list; });

            // 更新活跃事务的分支数
            if (_activeTransactions.TryGetValue(xid, out var activeTransaction))
            {
                activeTransaction.BranchCount++;
            }

            _logger.LogDebug("Branch register recorded, XID: {Xid}, BranchId: {BranchId}, ResourceId: {ResourceId}", 
                xid, branchId, resourceId);
        }

        public void RecordBranchCommit(string xid, long branchId)
        {
            if (_branchMetrics.TryGetValue(xid, out var branches))
            {
                var branch = branches.FirstOrDefault(b => b.BranchId == branchId);
                if (branch != null)
                {
                    branch.EndTime = DateTime.UtcNow;
                    branch.Status = BranchStatus.Committed;
                    branch.Duration = (long)(branch.EndTime.Value - branch.StartTime).TotalMilliseconds;

                    _logger.LogDebug("Branch commit recorded, XID: {Xid}, BranchId: {BranchId}", 
                        xid, branchId);
                }
            }
        }

        public void RecordBranchRollback(string xid, long branchId, Exception? exception = null)
        {
            if (_branchMetrics.TryGetValue(xid, out var branches))
            {
                var branch = branches.FirstOrDefault(b => b.BranchId == branchId);
                if (branch != null)
                {
                    branch.EndTime = DateTime.UtcNow;
                    branch.Status = BranchStatus.RolledBack;
                    branch.Duration = (long)(branch.EndTime.Value - branch.StartTime).TotalMilliseconds;
                    branch.Exception = exception;

                    _logger.LogDebug("Branch rollback recorded, XID: {Xid}, BranchId: {BranchId}, Exception: {Exception}",
                        xid, branchId, exception?.Message);
                }
            }
        }

        public void RecordTransaction(string transactionId, TransactionStatus status)
        {
            switch (status)
            {
                case TransactionStatus.Begin:
                    RecordTransactionBegin(transactionId, transactionId, "UNKNOWN");
                    break;
                case TransactionStatus.Committed:
                    if (_activeTransactions.TryGetValue(transactionId, out var activeTransaction))
                    {
                        var duration = (long)(DateTime.UtcNow - activeTransaction.StartTime).TotalMilliseconds;
                        RecordTransactionCommit(transactionId, duration);
                    }
                    break;
                case TransactionStatus.RolledBack:
                    if (_activeTransactions.TryGetValue(transactionId, out var rollbackTransaction))
                    {
                        var duration = (long)(DateTime.UtcNow - rollbackTransaction.StartTime).TotalMilliseconds;
                        RecordTransactionRollback(transactionId, duration);
                    }
                    break;
            }

            _logger.LogDebug("Transaction recorded, TransactionId: {TransactionId}, Status: {Status}",
                transactionId, status);
        }

        public void RecordBranch(long branchId, BranchStatus status)
        {
            // Find the branch in all transactions
            foreach (var branches in _branchMetrics.Values)
            {
                var branch = branches.FirstOrDefault(b => b.BranchId == branchId);
                if (branch != null)
                {
                    branch.Status = status;
                    branch.EndTime = DateTime.UtcNow;
                    branch.Duration = (long)(branch.EndTime.Value - branch.StartTime).TotalMilliseconds;

                    _logger.LogDebug("Branch recorded, BranchId: {BranchId}, Status: {Status}",
                        branchId, status);
                    break;
                }
            }
        }

        public TransactionStatistics GetTransactionStatistics(DateTime startTime, DateTime endTime)
        {
            lock (_statisticsLock)
            {
                return new TransactionStatistics
                {
                    TotalTransactions = _statistics.TotalTransactions,
                    CommittedTransactions = _statistics.CommittedTransactions,
                    RolledBackTransactions = _statistics.RolledBackTransactions,
                    ActiveTransactions = _statistics.ActiveTransactions,
                    TotalDuration = _statistics.TotalDuration,
                    MaxDuration = _statistics.MaxDuration,
                    MinDuration = _statistics.MinDuration,
                    AverageDuration = _statistics.CommittedTransactions > 0 
                        ? _statistics.TotalDuration / _statistics.CommittedTransactions 
                        : 0,
                    SuccessRate = _statistics.TotalTransactions > 0 
                        ? (double)_statistics.CommittedTransactions / _statistics.TotalTransactions * 100 
                        : 0
                };
            }
        }

        public TransactionMetrics GetTransactionMetrics(DateTime startTime, DateTime endTime)
        {
            var metrics = _transactionMetrics.Values
                .Where(m => m.StartTime >= startTime && m.EndTime <= endTime)
                .ToList();

            return new TransactionMetrics
            {
                Transactions = metrics,
                TotalCount = metrics.Count,
                CommittedCount = metrics.Count(m => m.Status == TransactionMonitorStatus.Committed),
                RolledBackCount = metrics.Count(m => m.Status == TransactionMonitorStatus.RolledBack),
                AverageDuration = metrics.Count > 0 
                    ? metrics.Sum(m => m.Duration) / metrics.Count 
                    : 0,
                MaxDuration = metrics.Count > 0 ? metrics.Max(m => m.Duration) : 0,
                MinDuration = metrics.Count > 0 ? metrics.Min(m => m.Duration) : 0
            };
        }

        public List<ActiveTransaction> GetActiveTransactions()
        {
            return _activeTransactions.Values.ToList();
        }

        public TransactionDetail? GetTransactionDetail(string xid)
        {
            if (!_transactionMetrics.TryGetValue(xid, out var transactionMetrics))
            {
                // 检查是否是活跃事务
                if (_activeTransactions.TryGetValue(xid, out var activeTransaction))
                {
                    var detail = new TransactionDetail
                    {
                        Xid = activeTransaction.Xid,
                        TransactionName = activeTransaction.TransactionName,
                        BranchType = activeTransaction.BranchType,
                        StartTime = activeTransaction.StartTime,
                        Status = activeTransaction.Status,
                        BranchCount = activeTransaction.BranchCount,
                        Exception = activeTransaction.Exception
                    };

                    // 添加分支信息
                    if (_branchMetrics.TryGetValue(xid, out var branches))
                    {
                        detail.Branches = branches.Select(b => new BranchDetail
                        {
                            BranchId = b.BranchId,
                            ResourceId = b.ResourceId,
                            BranchType = b.BranchType,
                            StartTime = b.StartTime,
                            EndTime = b.EndTime,
                            Duration = b.Duration,
                            Status = b.Status,
                            Exception = b.Exception
                        }).ToList();
                    }

                    return detail;
                }

                return null;
            }

            var transactionDetail = new TransactionDetail
            {
                Xid = transactionMetrics.Xid,
                TransactionName = transactionMetrics.TransactionName,
                BranchType = transactionMetrics.BranchType,
                StartTime = transactionMetrics.StartTime,
                EndTime = transactionMetrics.EndTime,
                Duration = transactionMetrics.Duration,
                Status = transactionMetrics.Status,
                Exception = transactionMetrics.Exception
            };

            // 添加分支信息
            if (_branchMetrics.TryGetValue(xid, out var transactionBranches))
            {
                transactionDetail.Branches = transactionBranches.Select(b => new BranchDetail
                {
                    BranchId = b.BranchId,
                    ResourceId = b.ResourceId,
                    BranchType = b.BranchType,
                    StartTime = b.StartTime,
                    EndTime = b.EndTime,
                    Duration = b.Duration,
                    Status = b.Status,
                    Exception = b.Exception
                }).ToList();
            }

            return transactionDetail;
        }

        public TransactionMetrics GetMetrics()
        {
            var now = DateTime.UtcNow;
            return GetTransactionMetrics(DateTime.MinValue, now);
        }

        public void ResetMetrics()
        {
            lock (_statisticsLock)
            {
                _statistics = new TransactionStatistics();
            }
            _transactionMetrics.Clear();
            _branchMetrics.Clear();
            _activeTransactions.Clear();

            _logger.LogInformation("Transaction metrics reset");
        }

        /// <summary>
        /// 后台清理任务
        /// </summary>
        private async Task CleanupTaskAsync()
        {
            while (true)
            {
                try
                {
                    await Task.Delay(TimeSpan.FromMinutes(10));

                    var config = _configuration.CurrentValue;
                    var cutoffTime = DateTime.UtcNow.AddHours(-config.MetricsRetentionHours);

                    // 清理过期的事务指标
                    var expiredKeys = _transactionMetrics
                        .Where(kvp => kvp.Value.EndTime < cutoffTime)
                        .Select(kvp => kvp.Key)
                        .ToList();

                    foreach (var key in expiredKeys)
                    {
                        _transactionMetrics.TryRemove(key, out _);
                        _branchMetrics.TryRemove(key, out _);
                    }

                    // 清理长时间未完成的活跃事务
                    var staleActiveTransactions = _activeTransactions
                        .Where(kvp => kvp.Value.StartTime < cutoffTime)
                        .ToList();

                    foreach (var kvp in staleActiveTransactions)
                    {
                        if (_activeTransactions.TryRemove(kvp.Key, out var activeTransaction))
                        {
                            activeTransaction.Status = TransactionMonitorStatus.Timeout;
                            activeTransaction.EndTime = DateTime.UtcNow;
                            activeTransaction.Duration = (long)(activeTransaction.EndTime.Value - activeTransaction.StartTime).TotalMilliseconds;

                            // 记录为超时事务
                            var metrics = new TransactionMetrics
                            {
                                Xid = activeTransaction.Xid,
                                TransactionName = activeTransaction.TransactionName,
                                BranchType = activeTransaction.BranchType,
                                StartTime = activeTransaction.StartTime,
                                EndTime = activeTransaction.EndTime ?? DateTime.UtcNow,
                                Duration = activeTransaction.Duration,
                                Status = TransactionMonitorStatus.Timeout
                            };

                            _transactionMetrics.TryAdd(activeTransaction.Xid, metrics);

                            // 更新统计信息
                            lock (_statisticsLock)
                            {
                                _statistics.ActiveTransactions--;
                                _statistics.TimeoutTransactions++;
                            }

                            _logger.LogWarning("Active transaction timed out, XID: {Xid}, Duration: {Duration}ms", 
                                activeTransaction.Xid, activeTransaction.Duration);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error in cleanup task");
                }
            }
        }
    }

    /// <summary>
    /// 事务监控状态
    /// </summary>
    public enum TransactionMonitorStatus
    {
        /// <summary>
        /// 活跃
        /// </summary>
        Active,

        /// <summary>
        /// 已提交
        /// </summary>
        Committed,

        /// <summary>
        /// 已回滚
        /// </summary>
        RolledBack,

        /// <summary>
        /// 超时
        /// </summary>
        Timeout,

        /// <summary>
        /// 失败
        /// </summary>
        Failed
    }

    /// <summary>
    /// 分支状态
    /// </summary>
    /// <summary>
    /// 活跃事务
    /// </summary>
    public class ActiveTransaction
    {
        /// <summary>
        /// 全局事务ID
        /// </summary>
        public string Xid { get; set; } = string.Empty;

        /// <summary>
        /// 事务名称
        /// </summary>
        public string TransactionName { get; set; } = string.Empty;

        /// <summary>
        /// 分支类型
        /// </summary>
        public string BranchType { get; set; } = string.Empty;

        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartTime { get; set; }

        /// <summary>
        /// 结束时间
        /// </summary>
        public DateTime? EndTime { get; set; }

        /// <summary>
        /// 持续时间（毫秒）
        /// </summary>
        public long Duration { get; set; }

        /// <summary>
        /// 状态
        /// </summary>
        public TransactionMonitorStatus Status { get; set; }

        /// <summary>
        /// 分支数量
        /// </summary>
        public int BranchCount { get; set; }

        /// <summary>
        /// 异常信息
        /// </summary>
        public Exception? Exception { get; set; }
    }

    /// <summary>
    /// 事务指标
    /// </summary>
    public class TransactionMetrics
    {
        /// <summary>
        /// 全局事务ID
        /// </summary>
        public string Xid { get; set; } = string.Empty;

        /// <summary>
        /// 事务名称
        /// </summary>
        public string TransactionName { get; set; } = string.Empty;

        /// <summary>
        /// 分支类型
        /// </summary>
        public string BranchType { get; set; } = string.Empty;

        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartTime { get; set; }

        /// <summary>
        /// 结束时间
        /// </summary>
        public DateTime EndTime { get; set; }

        /// <summary>
        /// 持续时间（毫秒）
        /// </summary>
        public long Duration { get; set; }

        /// <summary>
        /// 状态
        /// </summary>
        public TransactionMonitorStatus Status { get; set; }

        /// <summary>
        /// 异常信息
        /// </summary>
        public Exception? Exception { get; set; }

        /// <summary>
        /// 事务列表（用于聚合指标）
        /// </summary>
        public List<TransactionMetrics> Transactions { get; set; } = new List<TransactionMetrics>();

        /// <summary>
        /// 总数量
        /// </summary>
        public int TotalCount { get; set; }

        /// <summary>
        /// 已提交数量
        /// </summary>
        public int CommittedCount { get; set; }

        /// <summary>
        /// 已回滚数量
        /// </summary>
        public int RolledBackCount { get; set; }

        /// <summary>
        /// 平均持续时间（毫秒）
        /// </summary>
        public long AverageDuration { get; set; }

        /// <summary>
        /// 最大持续时间（毫秒）
        /// </summary>
        public long MaxDuration { get; set; }

        /// <summary>
        /// 最小持续时间（毫秒）
        /// </summary>
        public long MinDuration { get; set; }
    }

    /// <summary>
    /// 分支指标
    /// </summary>
    public class BranchMetrics
    {
        /// <summary>
        /// 全局事务ID
        /// </summary>
        public string Xid { get; set; } = string.Empty;

        /// <summary>
        /// 分支ID
        /// </summary>
        public long BranchId { get; set; }

        /// <summary>
        /// 资源ID
        /// </summary>
        public string ResourceId { get; set; } = string.Empty;

        /// <summary>
        /// 分支类型
        /// </summary>
        public string BranchType { get; set; } = string.Empty;

        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartTime { get; set; }

        /// <summary>
        /// 结束时间
        /// </summary>
        public DateTime? EndTime { get; set; }

        /// <summary>
        /// 持续时间（毫秒）
        /// </summary>
        public long Duration { get; set; }

        /// <summary>
        /// 状态
        /// </summary>
        public BranchStatus Status { get; set; }

        /// <summary>
        /// 异常信息
        /// </summary>
        public Exception? Exception { get; set; }
    }

    /// <summary>
    /// 事务统计信息
    /// </summary>
    public class TransactionStatistics
    {
        /// <summary>
        /// 总事务数
        /// </summary>
        public long TotalTransactions { get; set; }

        /// <summary>
        /// 已提交事务数
        /// </summary>
        public long CommittedTransactions { get; set; }

        /// <summary>
        /// 已回滚事务数
        /// </summary>
        public long RolledBackTransactions { get; set; }

        /// <summary>
        /// 超时事务数
        /// </summary>
        public long TimeoutTransactions { get; set; }

        /// <summary>
        /// 活跃事务数
        /// </summary>
        public long ActiveTransactions { get; set; }

        /// <summary>
        /// 总持续时间（毫秒）
        /// </summary>
        public long TotalDuration { get; set; }

        /// <summary>
        /// 最大持续时间（毫秒）
        /// </summary>
        public long MaxDuration { get; set; }

        /// <summary>
        /// 最小持续时间（毫秒）
        /// </summary>
        public long MinDuration { get; set; }

        /// <summary>
        /// 平均持续时间（毫秒）
        /// </summary>
        public long AverageDuration { get; set; }

        /// <summary>
        /// 成功率（百分比）
        /// </summary>
        public double SuccessRate { get; set; }
    }

    /// <summary>
    /// 事务详情
    /// </summary>
    public class TransactionDetail
    {
        /// <summary>
        /// 全局事务ID
        /// </summary>
        public string Xid { get; set; } = string.Empty;

        /// <summary>
        /// 事务名称
        /// </summary>
        public string TransactionName { get; set; } = string.Empty;

        /// <summary>
        /// 分支类型
        /// </summary>
        public string BranchType { get; set; } = string.Empty;

        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartTime { get; set; }

        /// <summary>
        /// 结束时间
        /// </summary>
        public DateTime? EndTime { get; set; }

        /// <summary>
        /// 持续时间（毫秒）
        /// </summary>
        public long Duration { get; set; }

        /// <summary>
        /// 状态
        /// </summary>
        public TransactionMonitorStatus Status { get; set; }

        /// <summary>
        /// 分支数量
        /// </summary>
        public int BranchCount { get; set; }

        /// <summary>
        /// 分支列表
        /// </summary>
        public List<BranchDetail> Branches { get; set; } = new List<BranchDetail>();

        /// <summary>
        /// 异常信息
        /// </summary>
        public Exception? Exception { get; set; }
    }

    /// <summary>
    /// 分支详情
    /// </summary>
    public class BranchDetail
    {
        /// <summary>
        /// 分支ID
        /// </summary>
        public long BranchId { get; set; }

        /// <summary>
        /// 资源ID
        /// </summary>
        public string ResourceId { get; set; } = string.Empty;

        /// <summary>
        /// 分支类型
        /// </summary>
        public string BranchType { get; set; } = string.Empty;

        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartTime { get; set; }

        /// <summary>
        /// 结束时间
        /// </summary>
        public DateTime? EndTime { get; set; }

        /// <summary>
        /// 持续时间（毫秒）
        /// </summary>
        public long Duration { get; set; }

        /// <summary>
        /// 状态
        /// </summary>
        public BranchStatus Status { get; set; }

        /// <summary>
        /// 异常信息
        /// </summary>
        public Exception? Exception { get; set; }
    }
}